const jwt = require('jsonwebtoken');
const ApiResponse = require('../utils/response');
const logger = require('../utils/logger');

/**
 * 用户认证中间件
 * 验证JWT token并将用户信息添加到req.user
 */
const userAuth = (req, res, next) => {
  try {
    // 从请求头获取token
    const authHeader = req.headers.authorization;
    
    if (!authHeader) {
      return ApiResponse.unauthorized(res, '未提供认证令牌');
    }

    // 验证token格式 "Bearer <token>"
    const parts = authHeader.split(' ');
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
      return ApiResponse.unauthorized(res, '认证令牌格式错误');
    }

    const token = parts[1];

    // 验证token
    const decoded = jwt.verify(
      token,
      process.env.JWT_SECRET || 'xiqu-secret-key'
    );

    // 检查token类型
    if (decoded.type !== 'user') {
      return ApiResponse.unauthorized(res, '无效的认证令牌');
    }

    // 将用户信息添加到请求对象
    req.user = {
      userId: decoded.userId,
      phone: decoded.phone
    };

    next();

  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      logger.warn('无效的JWT令牌', { error: error.message });
      return ApiResponse.unauthorized(res, '无效的认证令牌');
    }
    
    if (error.name === 'TokenExpiredError') {
      logger.warn('JWT令牌已过期', { error: error.message });
      return ApiResponse.unauthorized(res, '认证令牌已过期，请重新登录');
    }

    logger.error('认证中间件错误', { error: error.message });
    return ApiResponse.serverError(res, '认证失败');
  }
};

/**
 * 可选的用户认证中间件
 * 如果提供了token则验证，否则继续执行（不阻断请求）
 */
const optionalUserAuth = (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    
    if (!authHeader) {
      return next();
    }

    const parts = authHeader.split(' ');
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
      return next();
    }

    const token = parts[1];

    try {
      const decoded = jwt.verify(
        token,
        process.env.JWT_SECRET || 'xiqu-secret-key'
      );

      if (decoded.type === 'user') {
        req.user = {
          userId: decoded.userId,
          phone: decoded.phone
        };
      }
    } catch (error) {
      // Token验证失败，但不阻断请求
      logger.debug('可选认证：token验证失败', { error: error.message });
    }

    next();

  } catch (error) {
    logger.error('可选认证中间件错误', { error: error.message });
    next();
  }
};

module.exports = { userAuth, optionalUserAuth };

